#include "Common.h"
#include "ReaderManager.h"
#include "TreeItem_Book.h"
#include "Widget_Reader.h"
#include "Widget_Start.h"

#include <qglobal.h>
#include <QtGui/QGridLayout>
#include <QTime>

namespace Jonathan
{
   ReaderManager* ReaderManager::s_Instance = 0;

   /**
    * @brief Gets the instance of the reader manager.
    *
    * @return Jonathan::ReaderManager * Reader manager instance.
    */
   ReaderManager* ReaderManager::GetInstance ()
   {
      if (!s_Instance)
         s_Instance = new ReaderManager();

      return s_Instance;
   }

   /**
    * @brief Initializes a new reader manager.
    *
    */
   ReaderManager::ReaderManager ()
   {
      this->m_TabMain = new XQTabWidget (this);
      this->m_TabMain->setTabsClosable (true);
      this->m_TabMain->setMovable (false);

      QTime time = QTime::currentTime();
      qsrand ((uint)time.msec());

      Widget_Start* startTab = new Widget_Start (this->m_TabMain);
      this->m_TabMain->addTab (startTab, Common::GetIcon (Jonathan::ICON_Start), "Start");

      QGridLayout* layout = new QGridLayout (this);
      layout->setMargin (0);
      layout->addWidget (this->m_TabMain);
      this->setLayout (layout);
   }

   /**
    * @brief Starts a reader with the given properties.
    *
    * @param book Book database tree item.
    * @param subBook Sub book to open, if any.
    * @param chapter Chapter to start in.
    */
   void ReaderManager::StartReading (TreeItem_Book *book, QString subBook, QString chapter)
   {
      Widget_Reader *reader = new Widget_Reader (this->m_TabMain);
      int addIndex = this->m_TabMain->addTab (reader, Common::GetIcon (Jonathan::ICON_Book),
                                              book->GetBookAbbreviation ());
      this->m_TabMain->setTabToolTip (addIndex, book->GetName ());
      this->m_TabMain->setCurrentIndex (addIndex);
      reader->SetTabIndex (addIndex);
      connect (reader, SIGNAL (TitleChanged (QString,int)),
               this->m_TabMain, SLOT (ChangeTabTitle (QString,int)));
      reader->Read (book, subBook, chapter);
   }
}
